import MySQLdb

class MySqlHelper:
    '''
    MySQL utility class
    '''

    def __init__(self, SQLINFO):
        try:
            import MySQLdb
        except (ImportError) as e:
            raise e
        try:
            host = SQLINFO['host']
            user = SQLINFO['user']
            passwd = SQLINFO['password']
            port = SQLINFO['port']
            db = SQLINFO['db']
            charset = SQLINFO['charset']
            self.conn = MySQLdb.connect(host=host, user=user, db=db, passwd=passwd, port=port, charset=charset)
            self.cursor = self.conn.cursor()
        except (Exception) as e:
            raise e

    '''
    commit and close connection
    '''

    def Finish(self):
        try:
            self.conn.commit()
            self.conn.close()
            self.cursor.close()
        except (Exception) as e:
            raise e

    '''
    create database
    '''

    def CreateDB(self, db):
        try:
            self.cursor.execute('create database %s' % db)
            self.Finish()
        except (Exception) as e:
            raise e

    '''
    execute SQL such as insert, update and delete
    '''

    def ExecuteNoQuery(self, SQLstring):
        try:
            count = self.cursor.execute(SQLstring)
            self.Finish()
            return count
        except (Exception) as e:
            raise e
            return -1

    '''
    execute SQL about select
    '''

    def ExecuteQuery(self, SQLstring):
        try:
            self.cursor.execute(SQLstring)
            result = self.cursor.fetchall()
            self.Finish()
            return result
        except (Exception) as e:
            raise e
            return None

'''
combine list and return string
'''
def GetStringForList(list):
    str = ''
    for elem in list:
        str += elem + ' '
    return str

################################################### test ###############################################################
if __name__ == "__main__":
    sql_info = {"host":"192.168.184.1", "user":"root", "password":"root", "port":3306, "db":"demo", "charset":"utf8"}
    my_sql_helper = MySqlHelper(sql_info)
    result = my_sql_helper.ExecuteQuery("select * from address")
    print(type(result))
    print(result)